package com.lushu.helpers.io
{
	import com.lushu.data.interfaces.IReader;
	import com.lushu.data.interfaces.IWriter;
	import com.lushu.events.ResourceEvent;
	import com.lushu.typedArrays.ArrayList;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.utils.ByteArray;
	
	import mx.controls.Alert;
	
	import parts.renderer.ProgressBarRenderer;
	
	public class GenericIO extends EventDispatcher implements IReader,IWriter
	{
		public static const XML_FILE : int = 0;
		public static const BITMAP_FILE : int = 1;
		
		private var fileInfo_ : XML;
		private var fileInfoAsBitmap_ : Bitmap;
		private var fileLocation_ : String;
		private var uploadPath_ : String;
		private var uploadProgress_ : ProgressBarRenderer;
		private var uploadQueue_ : ArrayList;
		private var uploadInProgress_ : Boolean;
		
		public function GenericIO(fileLocation : String)
		{
			fileLocation_ = fileLocation;
			uploadQueue_ = new ArrayList(0, Object);	
		}
		
		public function read(inputType : int = XML_FILE) : void
		{
			var urlRequest : URLRequest = new URLRequest(fileLocation_);
			var requestHeader:URLRequestHeader = new URLRequestHeader("Cache-Control","no-cache");
			urlRequest.requestHeaders=new Array(requestHeader);
			switch(inputType)
			{
				case XML_FILE : 
					var loader : URLLoader = new URLLoader(urlRequest);
					loader.dataFormat = URLLoaderDataFormat.BINARY;
					loader.addEventListener(Event.COMPLETE, loadFileAsXML, false, 0, true);
					loader.addEventListener(IOErrorEvent.IO_ERROR, onIoError);
					loader.load(urlRequest);
				break;
				
				case BITMAP_FILE :
					var loaderBit: Loader = new Loader();
					loaderBit.contentLoaderInfo.addEventListener(Event.COMPLETE, loadFileAsBitmap, false, 0, true);
					loaderBit.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIoError);
					loaderBit.load(urlRequest);
				break;
			}
		}
		
		private function onIoError(e : IOErrorEvent): void
		{
			trace("Cannot load "+fileLocation_);
		}
		
		private function loadFileAsXML(event : Event) : void
		{
			fileInfo_ = new XML(event.target.data);
			dispatchEvent(new ResourceEvent(ResourceEvent.FILE_LOADED));
		}
		
		private function loadFileAsBitmap(event : Event) : void
		{
			var loader : Loader = Loader(event.target.loader);
			fileInfoAsBitmap_ = Bitmap(loader.content);
			dispatchEvent(new ResourceEvent(ResourceEvent.FILE_LOADED));
		}
		
		public function writeXML(xmlData : XML, fileName : String, uploadPath : String) : void
		{
			try
			{
				var file : File = File.createTempFile();
			}
			catch(e : IOErrorEvent)
			{
				trace("toto");
			}
			var stream : FileStream = new FileStream();
			
			var str:String="<?xml version=\"1.0\"?>\n"+xmlData.toXMLString();
			str = str.replace(/\r/g, "\n");
			str = str.replace(/\n/g, File.lineEnding);
			
			stream.open(file, FileMode.WRITE);
			stream.writeUTFBytes(str);
			stream.close();
			
			addToUploadQueue(file, fileName, uploadPath);
		}
		
    	private function progressHandler(event:ProgressEvent):void 
    	{
			var file:File = File(event.target);
			uploadProgress_.updateProgress(event.bytesLoaded, event.bytesTotal);      
		}
		
		private function completeHandler(e : Event) : void
		{
			//PopUpManager.removePopUp(uploadProgress_);
			var uploadObject : Object = uploadQueue_.removeLast();
			if(uploadObject != null)
			{
				upload(uploadObject.file, uploadObject.name, uploadObject.path);
			}
			else
			{
				uploadInProgress_ = false;
				Alert.show("Sauvegarde réussie");
			}
		}
		
		public function writePNG(pngImg : ByteArray, fileName : String, uploadPath : String) : void
		{
			var file : File = File.createTempFile();
			var stream : FileStream = new FileStream();
			
			stream.open(file, FileMode.WRITE);
			stream.writeBytes(pngImg);
			stream.close();
			
			addToUploadQueue(file, fileName, uploadPath);
		}
		
		private function addToUploadQueue(file : File, fileName : String, uploadPath : String) : void
		{
			if(!uploadInProgress_)
			{ // C'est le seul element donc on lance l'upload
				upload(file, fileName, uploadPath);
			}
			else
			{
				uploadQueue_.addItem({file : file, name : fileName, path : uploadPath});
			} 
		}
		private function upload(file : File, fileName : String, uploadPath : String) : void
		{
			uploadInProgress_ = true;
			var request : URLRequest = new URLRequest(uploadPath+"?name="+fileName);
    		
			//file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			file.addEventListener(Event.COMPLETE, completeHandler);
			
			
			file.upload(request);
		}
		
		public function getFileData() : XML
		{
			return fileInfo_;
		}
		
		public function getFileDataAsBitmap() : Bitmap
		{
			return fileInfoAsBitmap_;
		}
	}
}